package com.android.basiclib.base;

import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;


import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.android.basiclib.R;
import com.android.basiclib.entity.LoadAction;
import com.android.basiclib.receiver.ConnectivityReceiver;
import com.android.basiclib.uitls.ActivityManage;
import com.android.basiclib.uitls.StatusBarUtils;
import com.android.basiclib.uitls.TUtil;


/**
 * BaseActivityWithPlaceholder 在此基础上添加占位loading
 */
public abstract class BaseActivityWithPlaceholder<P extends BaseViewModel> extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener {

    /**
     * 获取Context对象
     */
    protected Activity mActivity;
    protected Context mContext;
    protected Toolbar mBaseToolbar;
    protected TextView mTvToolbarTitle;
    protected ImageView mIvToolbarRightIcon;
    protected TextView mTvRightText;
    protected P mViewModel;
    protected FrameLayout mPlaceholderView;
    protected FrameLayout mContentView;
    protected LinearLayout mErrorView;
    protected TextView mErrorText;
    protected boolean isFirstEnter = true;

    /**
     * 获取layout的id，具体由子类实现
     */
    protected abstract int getLayoutResId();

    /**
     * 其他的初始化操作
     */
    protected abstract void init();

    /**
     * 从intent中解析数据，具体子类来实现
     */
    protected void getDataFromIntent(Intent intent) {
    }

    /**
     * 设置顶部状态栏的颜色（默认为蓝色）
     */
    protected int setStatusBarColor() {
        //项目需要为设置白底黑字
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            return Color.parseColor("#ffffff");
        }
        return Color.parseColor("#B0B0B0");

        //默认为设置
//        return ContextCompat.getColor(mContext, R.color.colorPrimary);
    }

    /**
     * 动态的设置状态栏颜色
     * 当颜色为白色的时候显示白底黑字
     * 其他颜色为其他颜色底白色字
     */
    protected void setStatusBarColor(int color) {

        if (color == Color.WHITE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                StatusBarUtils.setColor(this, Color.WHITE);
            }

        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                StatusBarUtils.setColor(this, color);
            }
        }
    }

    /**
     * 跳转页面
     */
    protected void GotoActivity(Class clazz) {
        startActivity(new Intent(mActivity, clazz));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = getLayoutInflater().inflate(R.layout.base_activity_placeholder, null);
        mPlaceholderView = view.findViewById(R.id.view_placeholder);
        mContentView = view.findViewById(R.id.view_content);
        mErrorView = view.findViewById(R.id.view_error);
        mErrorText = view.findViewById(R.id.erroe_text);

        View realContentView = getLayoutInflater().inflate(getLayoutResId(), null);
        mContentView.addView(realContentView);

        setContentView(view);

        mActivity = this;
        mContext = this.getApplicationContext();

        mViewModel = createViewModel();
        //观察网络数据状态
        if (mViewModel != null) {
            mViewModel.getActionLiveData().observe(this, stateObserver);
        }


        //设置当前页面的顶部状态栏背景.
        StatusBarUtils.setColor(this, setStatusBarColor());

        //获取intent传递的数据
        if (getIntent() != null) {
            getDataFromIntent(getIntent());
        }

        //设置竖屏展示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        /** 管理Activity的栈 **/
        ActivityManage.addActivity(this);

        mViewModel = createViewModel();

        if (needRegisterNetworkChangeObserver())
            ConnectivityReceiver.registerObserver(this);

        initTitle();
        init();
        //观察其他的数据
        dataObserver();
    }

    protected abstract void dataObserver();

    /**
     * 初始化ViewModel去执行它的方法获取数据
     */
    protected P createViewModel() {
        Object o = TUtil.getInstance(this, 0);
        if (o != null) {
            try {
                return ViewModelProviders.of(this, new AutoViewModelFactory(this)).get((Class<P>) o);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 是否需要注册监听网络变换
     */
    protected boolean needRegisterNetworkChangeObserver() {
        return true;
    }

    /**
     * 初始化标题
     */
    protected void initTitle() {
        mBaseToolbar = (Toolbar) findViewById(R.id.comm_toolbar);
        mTvToolbarTitle = (TextView) findViewById(R.id.tv_toolbar_title);
        mIvToolbarRightIcon = (ImageView) findViewById(R.id.iv_right_icon);
        mTvRightText = (TextView) findViewById(R.id.tv_right_text);


        if (mBaseToolbar != null) {
            setSupportActionBar(mBaseToolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
//            mBaseToolbar.setNavigationIcon(R.drawable.);
//            mBaseToolbar.setNavigationOnClickListener(view -> onBackPressed());
            mBaseToolbar.setNavigationOnClickListener(view -> finish());
            if (mTvToolbarTitle != null) {
                mTvToolbarTitle.setText(setToolbarTitle());
            }
            if (mIvToolbarRightIcon != null) {
                mIvToolbarRightIcon.setVisibility(View.VISIBLE);
                mTvRightText.setVisibility(View.GONE);
                mIvToolbarRightIcon.setImageResource(setToolbarRightIconRes());
            }
            if (mTvRightText != null) {
                if (!TextUtils.isEmpty(setToolbarRightText())) {
                    mIvToolbarRightIcon.setVisibility(View.GONE);
                    mTvRightText.setVisibility(View.VISIBLE);
                    mTvRightText.setText(setToolbarRightText());
                }

            }
        }
    }

    protected String setToolbarRightText() {
        return "";
    }

    /**
     * 设置toolbar的右侧图标,由子类重写
     */
    protected int setToolbarRightIconRes() {
        return 0;
    }

    /**
     * 设置toolbar的title,由子类重写
     */
    protected CharSequence setToolbarTitle() {
        return "";
    }


    /**
     * 只映射了onDestroy方法
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        ActivityManage.removeActivity(this);

        //解绑，取消Presenter订阅
        if (mViewModel != null)
            mViewModel.cleanTask();

        if (needRegisterNetworkChangeObserver())
            ConnectivityReceiver.unregisterObserver(this);
    }

    /**
     * 设置应用的字体不随系统的字体大小而改变
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值    //当接收系统的字体大小改变的时候。重置为默认
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }


    /* =========================== BaseView的三个回调 =====================================**/

    protected Observer stateObserver = new Observer<LoadAction>() {
        @Override
        public void onChanged(@Nullable LoadAction loadAction) {
            if (loadAction != null) {
                if (LoadAction.STATE_NORMAL == loadAction.action) {
                    showStateNormal();
                } else if (LoadAction.STATE_ERROR == loadAction.action) {
                    showStateError(loadAction.message);
                } else if (LoadAction.STATE_SUCCESS == loadAction.action) {
                    showStateSuccess();
                } else if (LoadAction.STATE_LOADING == loadAction.action) {
                    showStateLoading(loadAction.message);
                } else if (LoadAction.STATE_NO_DATA == loadAction.action) {
                    showStateNoData();
                }
            }
        }
    };

    protected void showStateNormal() {
    }

    protected void showStateLoading(String message) {
        if (isFirstEnter) {
            showPlaceholderView();
        }
    }

    protected void showStateError(String message) {
        if (isFirstEnter) {
            showErrorView(message);
            isFirstEnter = false;
        }
    }

    protected void showStateSuccess() {
        if (isFirstEnter) {
            showContentView();
            isFirstEnter = false;
        }

    }

    protected void showStateNoData() {
        if (isFirstEnter) {
            showErrorView("No Data");
            isFirstEnter = false;
        }

    }


    /**
     * 展示占位布局
     */
    private void showPlaceholderView() {
        //加载自定义的占位布局
        mPlaceholderView.removeAllViews();
        View placeholderView = getLayoutInflater().inflate(setPlaceholderViewRes(), null);
        mPlaceholderView.addView(placeholderView);
        mPlaceholderView.setVisibility(View.VISIBLE);
        mContentView.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);
    }


    /**
     * 展示内容布局
     */
    private void showContentView() {
        mPlaceholderView.removeAllViews();
        mPlaceholderView.setVisibility(View.GONE);
        mContentView.setVisibility(View.VISIBLE);
        mErrorView.setVisibility(View.GONE);
    }

    /**
     * 展示错误布局
     */
    private void showErrorView(String msg) {
        mPlaceholderView.removeAllViews();
        mErrorText.setText(msg);
        mPlaceholderView.setVisibility(View.GONE);
        mContentView.setVisibility(View.GONE);
        mErrorView.setVisibility(View.VISIBLE);
    }

    /**
     * 设置专属的占位布局
     */
    public int setPlaceholderViewRes() {
        return R.layout.layout_placeholder2;
    }

}
